import axios from 'axios'
import {ElMessage} from 'element-plus'
import {useUserStore} from "@/stores/index.js";

// 创建axios实例
const request = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL, // Django后端地址
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 从userStore获取token
        const userStore = useUserStore()
        // 按照后端的要求拼接token数据
        const token = userStore.token
        if (token) {
            config.headers.Authorization = `Token ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        const {data} = response
        // 如果后端返回的数据结构包含code字段

        if (data.code !== undefined) {
            if (data.code === 200) {
                return data
            } else {
                ElMessage.error("Request failed: ", data.message)
                return Promise.reject(new Error("Request failed: ", data.message))
            }
        }

        // 直接返回数据
        return data
    },
    error => {
        // 如果是请求被取消，不显示错误信息
        if (error.name === 'AbortError' || error.code === 'ERR_CANCELED') {
            return Promise.reject(error)
        }
        
        let message = 'Network Error'
        const userStore = useUserStore()
        if (error.response) {
            const {status, data} = error.response

            switch (status) {
                case 400:
                    message = data.info || 'Request parameter error'
                    break
                case 401:
                    message = 'Please login first'
                    // 清除用户信息并触发登录对话框
                    userStore.removeInfo()
                    window.dispatchEvent(new CustomEvent('show-login-dialog'))
                    break
                case 403:
                    message = 'Access denied'
                    break
                case 404:
                    message = 'The requested address does not exist'
                    break
                case 500:
                    message = 'Internal server error'
                    break
                default:
                    message = `Connection error ${status}`
            }
        }

        ElMessage.error(message)
        return Promise.reject(error)
    }
)

export default request